package cn.buddha.jec.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * @ClassName TongIOUtils
 * @Author 友野浩二
 * @Date 2020/4/13 11:05
 * @Description IO工具类
 * @Version 1.0
 */
@Slf4j
public class TongIOUtils {

    /**
     * @return java.lang.String
     * @Author 友野浩二
     * @Description // 获取指定输入流的所有字符文本内容，不会关闭输入流参数
     * @Date 2020/4/13 11:07
     * @Param [inputStream 字符文件输入流, charsetName 编码名称]
     */
    public static String getText(InputStream inputStream, String charsetName) {
        StringBuilder text = new StringBuilder();
        try (
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, charsetName));
        ) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                text.append(line).append(System.lineSeparator());
            }
        } catch (IOException e) {
            log.error("read text file from inputStream error: {}", e);
        }
        return text.toString();
    }

    /**
     * @return java.io.ByteArrayInputStream
     * @Author 友野浩二
     * @Description // 将 string 转换为 InputStream
     * @Date 2020/4/13 16:34
     * @Param [input, charsetName]
     */
    public static ByteArrayInputStream toInputStream(String input, String charsetName) {
        return new ByteArrayInputStream(input.getBytes(Charset.forName(charsetName)));
    }

}
